package cn.wen.image;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.wen.base.adapter.recyclerview.QuickRecyclerAdapter;
import cn.wen.base.adapter.recyclerview.QuickRecyclerViewHolder;
import cn.wen.base.decoration.LinearItemDecoration;
import cn.wen.base.dialog.QuickBuilder;
import cn.wen.base.dialog.QuickDialog;
import cn.wen.core.permission.PermissionListenerAdapter;
import cn.wen.core.permission.XPermission;
import cn.wen.core.titlebar.DefTitleBar;
import cn.wen.core.ui.AppActivity;
import cn.wen.image.bean.DirBean;
import cn.wen.image.bean.ImageBean;


/**
 * 图片选择的Activity
 */

public class SelectImageActivity extends AppActivity implements SelectImageHelper.OnImageLoadedListener {

    private static OnImageListener mImageListener;
    // 单选或者多选，int类型的type
    private int mMode = ImageHelper.MODE_MULTI;
    // int 类型的图片张数
    private int mMaxCount = 8;
    // boolean 类型的是否显示拍照按钮
    private boolean mShowCamera = true;
    // ArrayList<String> 已经选择好的图片
    private ArrayList<String> mResultList;
    // 仅仅选择
    private boolean mOnly = false;

    private RecyclerView mRecyclerView;
    private TextView mBtnShow;// 选择相片目录
    private TextView mBtnPreview;// 预览
    private SelectImageAdapter mAdapter;
    private List<DirBean> mDirs = new ArrayList<>();
    private int mDirPosition = 0;
    private QuickDialog mImageDialog;
    private DefTitleBar mDefTitleBar;
    private ImageHelper mPhotoHelper;
    private File mRestorePhotoFile;
    private final static String EXTRA_RESTORE_PHOTO = "extra_restore_photo";

    @Override
    protected void initData(Bundle savedInstanceState) {
        // 1.获取传递过来的参数
        Intent intent = getIntent();
        mMode = intent.getIntExtra(ImageHelper.EXTRA_SELECT_MODE, mMode);
        mMaxCount = intent.getIntExtra(ImageHelper.EXTRA_SELECT_COUNT, mMaxCount);
        mShowCamera = intent.getBooleanExtra(ImageHelper.EXTRA_SHOW_CAMERA, mShowCamera);
        mOnly = intent.getBooleanExtra(ImageHelper.EXTRA_SELECT_ONLY, mOnly);
        mResultList = intent.getStringArrayListExtra(ImageHelper.EXTRA_DEFAULT_SELECTED_LIST);
        if (mResultList == null) {
            mResultList = new ArrayList<>();
        }

    }

    @Override
    protected Object getContentLayout() {
        return R.layout.activity_select_image;
    }

    @Override
    protected void initTitle(DefTitleBar titleBar) {
        this.mDefTitleBar = titleBar;
        titleBar.setTitle("选择图片");
        titleBar.setRightTextClick(mRightTextClick);
    }

    @Override
    protected void initView(View view) {
        mRecyclerView = findViewById(R.id.recycler_view);
        mBtnShow = findViewById(R.id.btn_show_dialog);
        mBtnPreview = findViewById(R.id.btn_preview);
        mAdapter = new SelectImageAdapter(this, null, mResultList, mMaxCount);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnSelectListener(new SelectImageAdapter.OnSelectListener() {
            @Override
            public void onSelect(ArrayList<String> selectImages) {
                mResultList = selectImages;
                changeUI();
                // 如果仅仅是选择
                if (mOnly) {
                    sureSelect();
                }
            }

            @Override
            public void openCamera() {
                // 打开相机
                if (mPhotoHelper == null) {
                    mPhotoHelper = ImageHelper.with(getAppActivity());
                }
                mPhotoHelper.camera();
            }
        });
        // 选择目录的Dialog
        mBtnShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(v);
            }
        });

        mBtnPreview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mResultList == null || mResultList.size() <= 0) {
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putStringArrayList(ImageHelper.EXTRA_DEFAULT_SELECTED_LIST, mResultList);
                startActivity(PreviewActivity.class, bundle);
            }
        });

        // 申请权限
        new XPermission(getAppActivity())
                .permissions(Manifest.permission.READ_EXTERNAL_STORAGE)
                .request(new PermissionListenerAdapter() {
                    @Override
                    public void onSucceed() {
                        onStorageSucceed();
                    }
                });

    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mPhotoHelper != null) {
            mRestorePhotoFile = mPhotoHelper.getPhotoFile();
            if (mRestorePhotoFile != null) {
                outState.putSerializable(EXTRA_RESTORE_PHOTO, mRestorePhotoFile);
            }
        }

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (mPhotoHelper != null) {
            mRestorePhotoFile = (File) savedInstanceState.getSerializable(EXTRA_RESTORE_PHOTO);
            mPhotoHelper.setPhotoFile(mRestorePhotoFile);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 拍照的
        if (resultCode == RESULT_OK && requestCode == ImageHelper.CAMERA_REQUEST_CODE) {
            // 1.第一个要把图片加到集合
            File photoFile = mPhotoHelper.getPhotoFile();
            if (photoFile.exists() && photoFile.isFile()) {
                mResultList.add(photoFile.getAbsolutePath());
                // 3.通知系统本地有图片改变，下次进来可以找到这张图片
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(photoFile)));
                // 2.调用sureSelect()方法
                sureSelect();
            }
        }
    }


    /**
     * 加载图片
     */
    private void onStorageSucceed() {
        SelectImageHelper
                .with(this)
                .loadAllImage(this);
        changeUI();
    }

    private void changeUI() {
        int size = mResultList.size();
        mDefTitleBar.setRightText("完成(" + size + "/" + mMaxCount + ")");
        if (size <= 0) {
            mDefTitleBar.setRightTextColor("#ffcccccc");
            mBtnPreview.setTextColor(Color.parseColor("#ffcccccc"));
        } else {
            mDefTitleBar.setRightTextColor("#ffffffff");
            mBtnPreview.setTextColor(Color.parseColor("#ffffffff"));
        }
    }

    @Override
    public void onImageLoaded(List<ImageBean> images, Map<String, List<ImageBean>> dirMap) {
        // mDirMap = dirMap;
        mDirs.clear();
        DirBean dirBean = null;
        for (Map.Entry<String, List<ImageBean>> me : dirMap.entrySet()) {
            String key = me.getKey();
            List<ImageBean> value = me.getValue();
            dirBean = new DirBean();
            dirBean.images = value;
            dirBean.dir = key;
            dirBean.count = value.size() + "";
            if (value.size() > 0) {
                dirBean.firstImagePath = value.get(0).path;
                dirBean.dirName = value.get(0).dirName;
            }
            mDirs.add(dirBean);
        }
        dirBean = null;
        setContentData(images);
    }

    private void setContentData(List<ImageBean> images) {
        mAdapter.clear();
        // 如果需要显示拍照，就在第一个位置上加一个空String
        if (mShowCamera) {
            ImageBean bean = new ImageBean();
            mAdapter.add(bean);
        }
        mAdapter.addAll(images);
    }

    /**
     * 选择目录的Dialog
     *
     * @param view
     */
    public void showDialog(View view) {
        if (mImageDialog == null) {
            RecyclerView mPopView = (RecyclerView) LayoutInflater.from(this).inflate(R.layout.item_select_dialog, null, false);
            mPopView.setLayoutManager(new LinearLayoutManager(this));
            mPopView.addItemDecoration(new LinearItemDecoration(this));
            mPopView.setAdapter(new QuickRecyclerAdapter<DirBean>(this, mDirs, R.layout.item_select_dir) {
                @Override
                protected void convert(QuickRecyclerViewHolder holder, final DirBean item, final int position) {
                    if (position == 0) {
                        item.dirName = "所有图片";
                    }
                    holder.setText(R.id.dir_name, item.dirName);
                    holder.setText(R.id.dir_count, item.count);
                    holder.displayImage(R.id.dir_image, item.firstImagePath);
                    holder.setVisible(R.id.dir_right_image, View.INVISIBLE);
                    if (position == mDirPosition) {
                        holder.setVisible(R.id.dir_right_image, View.VISIBLE);
                    }
                    // 点击事件
                    holder.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (position != mDirPosition) {
                                mDirPosition = position;
                                notifyDataSetChanged();
                                setContentData(item.images);
                                mBtnShow.setText(item.dirName);
                            }
                            mImageDialog.dismiss();
                        }
                    });
                }


            });

            mImageDialog = QuickBuilder.create(this)
                    .fullWidth()
                    .fromBottom(true)
                    .setContentView(mPopView)
                    .setHeight(getDialogHeight())
                    .create();
        }

        mImageDialog.show();

    }

    public int getDialogHeight() {
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        return (int) (wm.getDefaultDisplay().getHeight() * 0.75f);
    }

    /**
     * 右边文本--完成点击事件
     */
    private View.OnClickListener mRightTextClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int size = mResultList.size();
            if (size <= 0) {
                return;
            }
            sureSelect();
        }
    };

    private void sureSelect() {
        // 选择好的图片传过去
        Intent intent = new Intent();
        intent.putStringArrayListExtra(ImageHelper.EXTRA_RESULT, mResultList);
        setResult(RESULT_OK, intent);
        if (mImageListener != null) {
            mImageListener.onImageSelected(mResultList);
        }
        // 关闭当前页面
        finish();
    }

    @Override
    protected void onDestroy() {
        mImageListener = null;
        super.onDestroy();
    }

    public static void setImageListener(OnImageListener imageListener) {
        mImageListener = imageListener;
    }
}
